import os
import os.path
import time

from xml.dom import minidom
from time import gmtime, strftime

def retrieveInfoXml(path, id):
    """seek into a parsed xml document a match with a specific ID
        Return value corresponding to the Id"""
    
    xmlDocument=minidom.parse(path)
    myResult = []
    myRefList=xmlDocument.getElementsByTagName("ref")
    for k in myRefList:
        valref=k.attributes["id"]
        if valref.value==id:
            myResult.append(k.firstChild.data)
            break
    return myResult

def retrieveAllXml(path):
    xmlDocument=minidom.parse(path)
    myResult = []
    myRefList=xmlDocument.getElementsByTagName("ref")
    for k in myRefList:
        myResult.append("".join(k.firstChild.data))
    return myResult

def createXml(fileName,globalRef,li):
    logfile = open(fileName, 'w')
    logfile.write('<?xml version="1.0" ?>\n')
    logfile.write('<'+globalRef+'>\n')
    for x in li:
        #z = x.split("\\")
        logfile.write('<ref id="'+os.path.basename(x)+'">'+x+'</ref>\n')
    logfile.write('</'+globalRef+'>\n')
    logfile.close()
    
def createXmlBP(fileName,globalRef,li):
    logfile = open(fileName, 'w')
    logfile.write('<?xml version="1.0" ?>\n')
    logfile.write('<'+globalRef+'>\n')
    for x in li:
        z = x.split("_")
        logfile.write('<ref id="'+z[0]+'">'+x+'</ref>\n')
    logfile.write('</'+globalRef+'>\n')
    logfile.close()
    
def createXmlUP(fileName,globalRef,li):
    logfile = open(fileName, 'w')
    logfile.write('<?xml version="1.0" ?>\n')
    logfile.write('<'+globalRef+'>\n')
    for x in li:
        z = x.split("_")
        logfile.write('<ref id="'+z[0]+'">'+z[1]+'</ref>\n')
    logfile.write('</'+globalRef+'>\n')
    logfile.close()
    
def addToXml(pathfileName,li):
    if os.access(pathfileName,os.F_OK):
        list=retrieveAllXml(pathfileName)
        for x in li:
            z = x.split("\\")
            list.append(x)
        createXml(pathfileName,"GlobalRef",list)
    else:
        createXml(pathfileName,"GlobalRef",li)